package com.crm.business.crm.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.crm.business.admin.service.AdminFileService;
import com.crm.business.admin.service.AdminService;
import com.crm.business.admin.service.IAdminMessageService;
import com.crm.business.crm.service.*;
import com.crm.business.utils.UserCacheUtil;
import com.crm.business.utils.UserUtil;
import com.crm.common.constant.Constants;
import com.crm.common.core.redis.RedisCache;
import com.crm.common.crm.common.ElasticUtil;
import com.crm.common.crm.constant.CrmBusinessConstEnum;
import com.crm.common.crm.constant.CrmEnum;
import com.crm.common.crm.constant.CrmRepaidStatusEnum;
import com.crm.common.crm.constant.FieldEnum;
import com.crm.common.crm.entity.BO.*;
import com.crm.common.crm.entity.PO.*;
import com.crm.common.crm.entity.VO.CrmModelFiledVO;
import com.crm.common.enums.ErrorCodeConstants;
import com.crm.common.exception.CustomException;
import com.crm.common.ka.core.common.R;
import com.crm.common.ka.core.common.Result;
import com.crm.common.ka.core.entity.UserInfo;
import com.crm.common.ka.core.feign.admin.entity.AdminConfigBo;
import com.crm.common.ka.core.feign.admin.entity.AdminMessage;
import com.crm.common.ka.core.feign.admin.entity.AdminMessageEnum;
import com.crm.common.ka.core.servlet.upload.FileEntity;
import com.crm.common.utils.DateUtils;
import com.crm.common.utils.StringUtils;
import com.crm.common.utils.bean.BeanUtils;
import com.crm.common.utils.spring.SpringUtils;
import com.crm.common.utils.uuid.IdUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import static com.crm.common.utils.spring.SpringUtils.getBean;

@Service
@Slf4j
public class BillOrderApiServiceImpl {
// implements CrmPageService
//    @Autowired
//    ElasticsearchRestTemplate restTemplate;
//    @Autowired
//    private ElasticsearchRestTemplate elasticsearchRestTemplate;
//
//    @Autowired
//    private ICrmContractService crmContractService;
//    @Autowired
//    private ICrmReceivablesService crmReceivablesService;
//
//    @Autowired
//    private ICrmReFundService crmReFundService;
//
//    @Autowired
//    private ICrmNumberSettingService crmNumberSettingService;
//
//    @Autowired
//    private BillCrmOrderPoolService billCrmOrderPoolService;
//
//    @Autowired
//    private RedisCache redisCache;
//
//    @Autowired
//    private ICrmCustomerService crmCustomerService;
//    @Autowired
//    private ICrmStudentService crmStudentService;
//    @Autowired
//    private IAdminMessageService adminMessageService;
//    @Autowired
//    private ICrmLeadsService crmLeadsService;
//    @Autowired
//    private AdminService adminService;
//
//    public static void main(String[] args) {
//    }
//
//
//    /**
//     * 创建订单
//     *
//     * @param loanOrderBO
//     * @return
//     */
//    @Transactional
//    public Result addOrUpdateOrderData(BillCrmLoanOrderBO loanOrderBO) throws Exception {
//        log.info("订单数据: " + JSONObject.toJSONString(loanOrderBO));
//        String orgId = loanOrderBO.getOrgId();
//        if(loanOrderBO.getVerify()){
//            log.info("需要校验: " + loanOrderBO.getVerify());
//            String pushTime = redisCache.getCacheObject(Constants.ORG_PUSH_TIME + orgId);
//            if(StringUtils.isNotEmpty(pushTime)){
//                Date time = DateUtils.parseDate(pushTime,DateUtils.YYYYMMDDHHMMSS);
//                if(loanOrderBO.getCreateTime().before(time)){
//                    return R.ok();
//                }
//            }
//        }
//
//        CrmContract contract = crmContractService.queryContractByNum(loanOrderBO.getOrderNum());
//        if (!ObjectUtils.isEmpty(contract)) {
//            // 若账单绑定学员,查询该学员下是否存在线下补款合同
//            if(!ObjectUtils.isEmpty(contract.getCustomerId())){
//                QueryWrapper<CrmContract> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("customer_id", contract.getCustomerId());
//                queryWrapper.in("check_status", Arrays.asList(1,3));
//                queryWrapper.eq("contract_category", CrmBusinessConstEnum.账单类别_线下合同.getMsg());
//                List<CrmContract> crmContractList = crmContractService.list(queryWrapper);
//                if(!CollectionUtils.isEmpty(crmContractList)){
//                    // 若线下补款合同已产生回款则不在更新该账单
//                    CrmContract contract1 = crmContractList.get(0);
//                    QueryWrapper<CrmReceivables> receivablesQueryWrapper = new QueryWrapper<>();
//                    receivablesQueryWrapper.eq("contract_id", contract1.getContractId());
//                    receivablesQueryWrapper.eq("check_status", 1);
//                    List<CrmReceivables> crmReceivablesList = crmReceivablesService.query().getBaseMapper().selectList(receivablesQueryWrapper);
//                    if(!CollectionUtils.isEmpty(crmReceivablesList)){
//                        return R.error(99,"产生线下合同,不做处理");
//                    }
//                }
//            }
//
//           return getBean(BillOrderApiServiceImpl.class).updateOrderData(loanOrderBO);
//        }
//        String key = Constants.LOCK_BILL_INSERT_ORDER + loanOrderBO.getOrderNum();
//        String value = UUID.randomUUID().toString();
//        //加锁
//        boolean b = redisCache.lock(key, value, 10, TimeUnit.SECONDS);
//        if (!b) {
//            throw new CustomException(ErrorCodeConstants.LOCK_DATA.getMsg(), ErrorCodeConstants.LOCK_DATA.getCode());
//        }
//        try {
//            CrmContract crmContract = new CrmContract();
//            crmContract.setOrgName(loanOrderBO.getOrgName());
//            crmContract.setType(CrmBusinessConstEnum.账单类型_三方账单.getMsg());
//            crmContract.setNum(loanOrderBO.getOrderNum());
//            crmContract.setName(loanOrderBO.getCurriculumName());
//            crmContract.setCheckStatus(CrmBusinessConstEnum.审核状态_通过.getCode());
//            crmContract.setCheckTime(DateUtils.getNowDate());
//            crmContract.setOrderDate(loanOrderBO.getApplicationTime());
//            crmContract.setCreateTime(DateUtils.getNowDate());
//            crmContract.setPaymentTime(loanOrderBO.getApplicationTime());
//            crmContract.setStartTime(loanOrderBO.getApplicationTime());
//            crmContract.setEndTime(DateUtil.offsetMonth(DateUtils.getNowDate(), 12));
//            crmContract.setMoney(loanOrderBO.getLoanMoney());
//            crmContract.setPaymentType(CrmBusinessConstEnum.审核状态_账单.getMsg());
//            crmContract.setReceivedMoney(loanOrderBO.getCollectMoney());
//            crmContract.setUnreceivedMoney(loanOrderBO.getWaitRepaidMoney());
//            crmContract.setRefundMonery(loanOrderBO.getDropoutMoney());
//            crmContract.setDealStatus(CrmBusinessConstEnum.是否成交_已成交.getMsg());
//            crmContract.setDealTime(loanOrderBO.getApplicationTime());
//            crmContract.setCourseSource(loanOrderBO.getCurriculumName());
//            crmContract.setBillReturnType(loanOrderBO.getBillReturnType());
//            crmContract.setOrderPoolStatus(CrmBusinessConstEnum.账单状态_有效.getMsg());
//            crmContract.setContractCategory(CrmBusinessConstEnum.账单类别_账单合同.getMsg());
//            crmContract.setPreferentialMoney(loanOrderBO.getPreferMoney());
//
//            /**
//             * 查询账单池
//             */
//            QueryWrapper<BillCrmOrderPool> queryWrapper = new QueryWrapper<BillCrmOrderPool>();
//            BillCrmOrderPool billCrmOrderPool = billCrmOrderPoolService.getBaseMapper().selectOne(queryWrapper);
//            Long orderPoolId = billCrmOrderPool.getOrderPoolId();
//            // 设置过期时间
//            crmContract.setExpireTime(DateUtils.addDays(loanOrderBO.getApplicationTime(),billCrmOrderPool.getDayNum()));
//
//            crmContract.setOwnerOrderPool(orderPoolId.toString());
//            crmContract.setStudentName(loanOrderBO.getRealName());
//            crmContract.setPhone(loanOrderBO.getUserPhone());
//            crmContract.setPeriodsNum(loanOrderBO.getPeriods());
//            Integer repaidStatus = loanOrderBO.getRepaidStatus();
//            crmContract.setRepaymentStatus(CrmRepaidStatusEnum.parse(repaidStatus).getRemarks());
//            crmContract.setRiskLevel(loanOrderBO.getRiskLevel() == 0 ? CrmBusinessConstEnum.风险提示_正常.getMsg() : CrmBusinessConstEnum.风险提示_高风险.getMsg());
//            crmContract.setDropOutTime(loanOrderBO.getDropoutTime());
//            crmContract.setRefundMonery(loanOrderBO.getDropoutMoney());
//            crmContract.setContractType(CrmBusinessConstEnum.合同类型_首购.getMsg());
//            crmContract.setCollectPeriods(loanOrderBO.getCollectPeriods());
//            crmContract.setStudentStatus(repaidStatus == 5 ? CrmBusinessConstEnum.入学状态_已退学.getMsg() : CrmBusinessConstEnum.入学状态_已入学.getMsg());
//            crmContract.setBatchId(IdUtil.simpleUUID());
//            /*
//             保存大订单-合同
//             */
//            crmContractService.save(crmContract);
//            /*小订单*/
//            List<BillCrmLoanOrderDetailBO> crmLoanOrderDetailBOList = loanOrderBO.getCrmLoanOrderDetailBOList();
//            /*回款*/
//            List<CrmReceivables> crmReceivablesList = new ArrayList<>();
//            for (BillCrmLoanOrderDetailBO loanOrderDetailBO : crmLoanOrderDetailBOList) {
//                CrmReceivables crmReceivables = new CrmReceivables();
//                crmReceivables.setContractId(crmContract.getContractId());
//                crmReceivables.setCustomerId(crmContract.getCustomerId());
//                crmReceivables.setNumber(loanOrderDetailBO.getOrderNum());
//                crmReceivables.setCheckStatus(CrmBusinessConstEnum.审核状态_通过.getCode());
//                crmReceivables.setCheckTime(DateUtils.getNowDate());
//                crmReceivables.setPaymentTime(loanOrderDetailBO.getActualRepaymentDate());
//                crmReceivables.setBillReturnType(loanOrderBO.getBillReturnType());
//                crmReceivables.setMoney(loanOrderDetailBO.getActualRepaymentMoney());
//                crmReceivables.setRepaymentDueMoney(loanOrderDetailBO.getRepaymentDueMoney());
//                crmReceivables.setCreateTime(DateUtils.getNowDate());
//                crmReceivables.setStudentsCall(loanOrderDetailBO.getUserPhone());
//                crmReceivables.setCourseSource(loanOrderDetailBO.getCurriculumName());
//                crmReceivables.setThreePartOrderNo(loanOrderDetailBO.getOrderNumMaster());
//                crmReceivables.setCollectionType(CrmBusinessConstEnum.回款类型_账单回款.getMsg());
//                crmReceivables.setOwnerOrderPool(orderPoolId.toString());
//                crmReceivables.setType(CrmBusinessConstEnum.账单类型_三方账单.getMsg());
//                crmReceivables.setStudentName(loanOrderDetailBO.getRealName());
//                crmReceivables.setRepayPeriods(loanOrderDetailBO.getRepayPeriods());
//                crmReceivables.setCommissionMoney(loanOrderDetailBO.getServiceCharge());
//                crmReceivables.setOverdueTime(loanOrderDetailBO.getOverdueDate());
//                crmReceivables.setActualRepaymentDate(loanOrderDetailBO.getActualRepaymentDate());
//                crmReceivables.setRepaymentDueDate(loanOrderDetailBO.getRepaymentDueDate());
//                crmReceivables.setBatchId(IdUtil.simpleUUID());
//                crmReceivables.setPeriodsNum(loanOrderDetailBO.getPeriods());
//                crmReceivables.setOrderPoolStatus(CrmBusinessConstEnum.账单状态_有效.getMsg());
//                crmReceivables.setRepaymentStatus(CrmRepaidStatusEnum.parse(repaidStatus).getRemarks());
//                crmReceivables.setStudentStatus(repaidStatus == 5 ? CrmBusinessConstEnum.入学状态_已退学.getMsg() : CrmBusinessConstEnum.入学状态_已入学.getMsg());
//                crmReceivablesService.save(crmReceivables);
//                crmReceivablesList.add(crmReceivables);
//            }
//            //补款
//            BillCrmFinanceDropoutPaySubOrderBo subOrderBo = loanOrderBO.getDropoutPaySubOrderBo();
//
//            CrmReceivables crmReceivablesBk = new CrmReceivables();
//            if (!ObjectUtils.isEmpty(subOrderBo)) {
//                // 如果查询到补款订单,不做新增
//                QueryWrapper<CrmReceivables> queryWrapper1 = new QueryWrapper<>();
//                queryWrapper1.eq("number",subOrderBo.getPayOrderNum());
//                List<CrmReceivables> crmReceivablesBkList = crmReceivablesService.getBaseMapper().selectList(queryWrapper1);
//                if(CollectionUtils.isEmpty(crmReceivablesBkList)){
//                    crmReceivablesBk.setContractId(crmContract.getContractId());
//                    crmReceivablesBk.setCustomerId(crmContract.getCustomerId());
//                    crmReceivablesBk.setNumber(subOrderBo.getPayOrderNum());
//                    crmReceivablesBk.setCheckStatus(CrmBusinessConstEnum.审核状态_通过.getCode());
//                    crmReceivablesBk.setCheckTime(DateUtils.getNowDate());
//                    crmReceivablesBk.setPaymentTime(subOrderBo.getPayTime());
//                    crmReceivablesBk.setBillReturnType(loanOrderBO.getBillReturnType());
//                    crmReceivablesBk.setMoney(subOrderBo.getFillMoney());
//                    crmReceivablesBk.setRepaymentDueMoney(subOrderBo.getFillMoney());
//                    crmReceivablesBk.setCreateTime(DateUtils.getNowDate());
//                    crmReceivablesBk.setStudentsCall(subOrderBo.getUserPhone());
//                    crmReceivablesBk.setCourseSource(subOrderBo.getCurriculumName());
//                    crmReceivablesBk.setThreePartOrderNo(subOrderBo.getOrderNum());
//                    crmReceivablesBk.setCollectionType(CrmBusinessConstEnum.回款类型_退款补款.getMsg());
//                    crmReceivablesBk.setOwnerOrderPool(orderPoolId.toString());
//                    crmReceivablesBk.setType(CrmBusinessConstEnum.账单类型_三方账单.getMsg());
//                    crmReceivablesBk.setStudentName(subOrderBo.getRealName());
////            crmReceivables.setRepayPeriods(subOrderBo.getRepayPeriods());
//                    crmReceivablesBk.setCommissionMoney(subOrderBo.getServiceCharge());
////            crmReceivables.setOverdueTime(subOrderBo.getOverdueDate());
//                    crmReceivablesBk.setActualRepaymentDate(subOrderBo.getPayTime());
//                    crmReceivablesBk.setRepaymentDueDate(subOrderBo.getPayTime());
//                    crmReceivablesBk.setRepaymentStatus(CrmRepaidStatusEnum.parse(loanOrderBO.getRepaidStatus()).getRemarks());
//                    crmReceivablesBk.setStudentStatus(CrmBusinessConstEnum.入学状态_已退学.getMsg());
//                    crmReceivablesBk.setBatchId(IdUtil.simpleUUID());
//                    crmReceivablesBk.setOrderPoolStatus(CrmBusinessConstEnum.账单状态_有效.getMsg());
//                    crmReceivablesService.save(crmReceivablesBk);
//                }
//            }
//
//            CrmRefund orderRefund = null;
//            if(loanOrderBO.getRepaidStatus() == 5){
//                orderRefund = new CrmRefund();
//                // 设置账单退款数据
//                orderRefund.setContractId(crmContract.getContractId());
//                orderRefund.setCustomerId(crmContract.getCustomerId());
//                // 退款编号
//                List<AdminConfigBo> configList = adminService.queryConfigByName("numberSetting");
//                AdminConfigBo adminConfig = configList.stream().filter(config -> Objects.equals(CrmEnum.REFUND.getType().toString(), config.getValue())).collect(Collectors.toList()).get(0);
//                if (adminConfig.getStatus() == 1 && StrUtil.isEmpty(orderRefund.getNumber())) {
//                    String result = crmNumberSettingService.generateNumber(adminConfig, null);
//                    if(BeanUtil.isEmpty(orderRefund.getNumber())){
//                        orderRefund.setNumber(result);
//                    }
//                }
//                orderRefund.setCourseSource(loanOrderBO.getCurriculumName());
//                orderRefund.setCreateTime(DateUtils.getNowDate());
//                orderRefund.setUpdateTime(DateUtils.getNowDate());
//                orderRefund.setCreateUserId(0L);
//                orderRefund.setRefundCategory(CrmBusinessConstEnum.退款状态_账单退款.getMsg());
//                orderRefund.setContractCategory(CrmBusinessConstEnum.账单类别_账单合同.getMsg());
//                orderRefund.setContractMoney(loanOrderBO.getLoanMoney());
//                orderRefund.setMoney(new BigDecimal(0));
//                if (!ObjectUtils.isEmpty(subOrderBo)) {
//                    orderRefund.setBillMoney(subOrderBo.getFillMoney());
//                }else{
//                    orderRefund.setBillMoney(new BigDecimal(0));
//                }
//                orderRefund.setRefundDate(new Date());
//                orderRefund.setCheckStatus(CrmBusinessConstEnum.审核状态_通过.getCode());
//                orderRefund.setReturnTime(loanOrderBO.getApplicationTime());
//                crmReFundService.save(orderRefund);
//            }
//
//            // 做优惠支付子订单删除操作
//            QueryWrapper<CrmReceivables> queryWrapper1 = new QueryWrapper<>();
//            queryWrapper1.eq("contract_id", crmContract.getContractId());
//            queryWrapper1.ne("check_status", 7);
//            queryWrapper1.eq("collection_type", CrmBusinessConstEnum.回款类型_优惠补款.getMsg());
//            List<CrmReceivables> receivablesList = crmReceivablesService.list(queryWrapper1);
//            // 删除优惠支付
//            if(!CollectionUtils.isEmpty(receivablesList)){
//                UpdateWrapper<CrmReceivables> updateWrapper1 = new UpdateWrapper<>();
//                updateWrapper1.set("check_status", 7);
//                updateWrapper1.in("receivables_id", receivablesList.stream().map(CrmReceivables::getReceivablesId).collect(Collectors.toList()));
//                crmReceivablesService.update(updateWrapper1);
//            }
//
//            // 优惠支付
//            BillCrmFinancePreferentialOrderBo preferentialOrderBo = loanOrderBO.getPreferentialOrderBo();
//            CrmReceivables crmReceivablesYH = new CrmReceivables();
//            if(!ObjectUtils.isEmpty(preferentialOrderBo)){
//                QueryWrapper<CrmReceivables> receivablesWrapper = new QueryWrapper<>();
//                receivablesWrapper.eq("number",preferentialOrderBo.getOrderNum());
//                receivablesWrapper.ne("check_status", 7);
//                List<CrmReceivables> crmReceivablesYHList = crmReceivablesService.getBaseMapper().selectList(receivablesWrapper);
//                if(CollectionUtils.isEmpty(crmReceivablesYHList)){
//                    crmReceivablesYH.setContractId(crmContract.getContractId());
//                    crmReceivablesYH.setCustomerId(crmContract.getCustomerId());
//                    crmReceivablesYH.setNumber(preferentialOrderBo.getPreferOrderNum());
//                    crmReceivablesYH.setCheckStatus(CrmBusinessConstEnum.审核状态_通过.getCode());
//                    crmReceivablesYH.setCheckTime(DateUtils.getNowDate());
//                    crmReceivablesYH.setPaymentTime(preferentialOrderBo.getPayTime());
//                    crmReceivablesYH.setBillReturnType(loanOrderBO.getBillReturnType());
//                    if(preferentialOrderBo.getPayStatus() == 1){
//                        crmReceivablesYH.setMoney(preferentialOrderBo.getPreferPayMoney());
//                    }else{
//                        crmReceivablesYH.setMoney(new BigDecimal(0.00));
//                    }
//                    crmReceivablesYH.setRepaymentDueMoney(preferentialOrderBo.getPreferPayMoney());
//                    crmReceivablesYH.setCreateTime(DateUtils.getNowDate());
//                    crmReceivablesYH.setStudentsCall(preferentialOrderBo.getUserPhone());
//                    crmReceivablesYH.setCourseSource(preferentialOrderBo.getCurriculumName());
//                    crmReceivablesYH.setThreePartOrderNo(preferentialOrderBo.getOrderNum());
//                    crmReceivablesYH.setCollectionType(CrmBusinessConstEnum.回款类型_优惠补款.getMsg());
//                    crmReceivablesYH.setOwnerOrderPool(orderPoolId.toString());
//                    crmReceivablesYH.setType(CrmBusinessConstEnum.账单类型_三方账单.getMsg());
//                    crmReceivablesYH.setStudentName(preferentialOrderBo.getRealName());
//                    crmReceivablesYH.setCommissionMoney(preferentialOrderBo.getServiceCharge());
//                    crmReceivablesYH.setActualRepaymentDate(preferentialOrderBo.getPayTime());
//                    crmReceivablesYH.setRepaymentDueDate(preferentialOrderBo.getPayTime());
//                    if(CrmRepaidStatusEnum.已还清.getRemarks().equals(CrmRepaidStatusEnum.parse(loanOrderBO.getRepaidStatus()).getRemarks()) && preferentialOrderBo.getPayStatus() == 1){
//                        crmReceivablesYH.setRepaymentStatus(CrmRepaidStatusEnum.已还清.getRemarks());
//                    }else{
//                        crmReceivablesYH.setRepaymentStatus(CrmRepaidStatusEnum.还款中.getRemarks());
//                    }
//                    crmReceivablesYH.setStudentStatus(CrmBusinessConstEnum.入学状态_已入学.getMsg());
//                    crmReceivablesYH.setBatchId(IdUtil.simpleUUID());
//                    crmReceivablesYH.setOrderPoolStatus(CrmBusinessConstEnum.账单状态_有效.getMsg());
//                    crmReceivablesService.save(crmReceivablesYH);
//                }
//            }
//
//            // 删除优惠支付
//            if(!CollectionUtils.isEmpty(receivablesList)){
//                deletePage(receivablesList.stream().map(CrmReceivables::getReceivablesId).collect(Collectors.toList()),CrmEnum.RECEIVABLES.getIndex());
//            }
//
////            插入ES数据
//            CrmContractSaveBO crmModel = new CrmContractSaveBO();
//            crmModel.setEntity(BeanUtil.beanToMap(crmContract));
//            savePageByLable(crmModel, crmContract.getContractId(), false, CrmEnum.CONTRACT.getType());
//            for (CrmReceivables crmReceivables : crmReceivablesList) {
//                CrmModelSaveBO receivablesModel = new CrmModelSaveBO();
//                receivablesModel.setEntity(BeanUtil.beanToMap(crmReceivables));
//                receivablesModel.getEntity().put("contractNum", crmContract.getNum());
//                receivablesModel.getEntity().put("contractMoney", crmContract.getMoney());
//                savePageByLable(receivablesModel, crmReceivables.getReceivablesId(), false, CrmEnum.RECEIVABLES.getType());
//            }
//            //补款es
//            if (!ObjectUtils.isEmpty(subOrderBo)) {
//                CrmModelSaveBO receivablesModel = new CrmModelSaveBO();
//                receivablesModel.setEntity(BeanUtil.beanToMap(crmReceivablesBk));
//                receivablesModel.getEntity().put("contractNum", crmContract.getNum());
//                receivablesModel.getEntity().put("contractMoney", crmContract.getMoney());
//                savePageByLable(receivablesModel, crmReceivablesBk.getReceivablesId(), false, CrmEnum.RECEIVABLES.getType());
//            }
//
//            if(!ObjectUtils.isEmpty(orderRefund)){
//                CrmModelSaveBO refundModel = new CrmModelSaveBO();
//                refundModel.setEntity(BeanUtil.beanToMap(orderRefund));
//                refundModel.getEntity().put("contractNum", crmContract.getNum());
//                refundModel.getEntity().put("contractMoney", crmContract.getMoney());
//                savePageByLable(refundModel, orderRefund.getRefundId(), false, CrmEnum.REFUND.getType());
//            }
//            //优惠支付es
//
//            if (!ObjectUtils.isEmpty(preferentialOrderBo)) {
//                CrmModelSaveBO receivablesModel = new CrmModelSaveBO();
//                receivablesModel.setEntity(BeanUtil.beanToMap(crmReceivablesYH));
//                receivablesModel.getEntity().put("contractNum", crmContract.getNum());
//                receivablesModel.getEntity().put("contractMoney", crmContract.getMoney());
//                savePageByLable(receivablesModel, crmReceivablesYH.getReceivablesId(), false, CrmEnum.RECEIVABLES.getType());
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new RuntimeException("系统异常" + e);
//        } finally {
//            redisCache.unlock(key, value);
//        }
//        return R.ok();
//    }
//
//    /**
//     * 更新订单  还款 补款 退学
//     *
//     * @param loanOrderBO
//     * @return
//     */
//    public Result updateOrderData(BillCrmLoanOrderBO loanOrderBO) {
//        String orgId = loanOrderBO.getOrgId().toString();
//        String key = Constants.LOCK_BILL_INSERT_ORDER + loanOrderBO.getOrderNum();
//        String value = UUID.randomUUID().toString();
//
//        //加锁
//        boolean b = redisCache.lock(key, value, 10, TimeUnit.SECONDS);
//        if (!b) {
//            throw new CustomException(ErrorCodeConstants.LOCK_DATA.getMsg(), ErrorCodeConstants.LOCK_DATA.getCode());
//        }
//
//        try {
//            CrmContract oldContract = crmContractService.queryContractByNum(loanOrderBO.getOrderNum());
//            CrmContract crmContract = new CrmContract();
//            crmContract.setNum(loanOrderBO.getOrderNum());
//            crmContract.setReceivedMoney(loanOrderBO.getCollectMoney());
//            crmContract.setUnreceivedMoney(loanOrderBO.getWaitRepaidMoney());
//            crmContract.setRepaymentStatus(CrmRepaidStatusEnum.parse(loanOrderBO.getRepaidStatus()).getRemarks());
//            crmContract.setDropOutTime(loanOrderBO.getDropoutTime());
//            crmContract.setPreferentialMoney(loanOrderBO.getPreferMoney());
//            if(CrmRepaidStatusEnum.已退学.getType().equals(loanOrderBO.getRepaidStatus())){
//                crmContract.setRefundMonery(loanOrderBO.getWaitRepaidMoney());
//                crmContract.setStudentStatus(CrmBusinessConstEnum.入学状态_已退学.getMsg());
//            }
//            crmContract.setRepairMoney(loanOrderBO.getFillMoney());
//            crmContract.setCollectPeriods(loanOrderBO.getCollectPeriods());
//            List<BillCrmLoanOrderDetailBO> orderDetailBOList = loanOrderBO.getCrmLoanOrderDetailBOList();
//            /**
//             * 还款-更新最新还款时间
//             */
//            if (!CollectionUtils.isEmpty(orderDetailBOList)) {
//                List<BillCrmLoanOrderDetailBO> collect = orderDetailBOList.stream().filter(s -> s.getActualRepaymentDate() != null).collect(Collectors.toList());
//                if (!CollectionUtils.isEmpty(collect)){
//                    Optional<BillCrmLoanOrderDetailBO> optional = collect.stream().sorted(Comparator.comparing(BillCrmLoanOrderDetailBO::getActualRepaymentDate).reversed()).findFirst();
//                    BillCrmLoanOrderDetailBO loanOrderDetailBO = optional.get();
//                    crmContract.setRecentBackTime(loanOrderDetailBO.getActualRepaymentDate());
//                }
//
//            }
//            BillCrmFinanceDropoutPaySubOrderBo subOrderBo = loanOrderBO.getDropoutPaySubOrderBo();
//            // 优惠支付
//            BillCrmFinancePreferentialOrderBo preferentialOrderBo = loanOrderBO.getPreferentialOrderBo();
//            /**
//             * 补款-更新最新还款时间
//             */
//            if (!ObjectUtils.isEmpty(subOrderBo)) {
//                crmContract.setRecentBackTime(subOrderBo.getPayTime());
//            }
//            /**
//             * 优惠支付更新最新还款时间
//             */
//            if(!ObjectUtils.isEmpty(preferentialOrderBo)) {
//                crmContract.setRecentBackTime(preferentialOrderBo.getPayTime());
//            }
//            //更新合同
//            UpdateWrapper<CrmContract> updateWrapper = new UpdateWrapper();
//            updateWrapper.eq("num", loanOrderBO.getOrderNum());
//            crmContractService.update(crmContract, updateWrapper);
//            CrmContract queryContract = crmContractService.queryContractByNum(loanOrderBO.getOrderNum());
//
//            //更新回款
//            List<CrmReceivables> crmReceivablesList = new ArrayList<>();
//            if (!CollectionUtils.isEmpty(orderDetailBOList)) {
//                QueryWrapper<CrmReceivables> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("contract_id", queryContract.getContractId());
//                List<CrmReceivables> receivablesList = crmReceivablesService.list(queryWrapper);
//                //需要更新回款的list
//                for (BillCrmLoanOrderDetailBO loanOrderDetailBO : orderDetailBOList) {
//                    //查询小单子回款
//                    CrmReceivables receivables = receivablesList.stream().filter(CrmReceivables -> CrmReceivables.getNumber().equals(loanOrderDetailBO.getOrderNum())).findFirst().get();
//                    CrmReceivables crmReceivables = new CrmReceivables();
//                    crmReceivables.setReceivablesId(receivables.getReceivablesId());
//                    crmReceivables.setNumber(loanOrderDetailBO.getOrderNum());
//                    crmReceivables.setMoney(loanOrderDetailBO.getActualRepaymentMoney());
//                    crmReceivables.setUpdateTime(DateUtils.getNowDate());
//                    crmReceivables.setOverdueTime(loanOrderDetailBO.getOverdueDate());
//                    crmReceivables.setActualRepaymentDate(loanOrderDetailBO.getActualRepaymentDate());
//                    crmReceivables.setPaymentTime(loanOrderDetailBO.getActualRepaymentDate());
//                    crmReceivables.setRepaymentStatus(CrmRepaidStatusEnum.parse(loanOrderDetailBO.getRepaidStatus()).getRemarks());
//                    crmReceivables.setStudentStatus(loanOrderBO.getRepaidStatus() == 5 ? CrmBusinessConstEnum.入学状态_已退学.getMsg() : CrmBusinessConstEnum.入学状态_已入学.getMsg());
//                    crmReceivablesList.add(crmReceivables);
//                }
//                crmReceivablesService.updateBatchById(crmReceivablesList);
//            }
//            CrmReceivables crmReceivablesBk = new CrmReceivables();
//            //更新补款
//            if (!ObjectUtils.isEmpty(subOrderBo)) {
//                CrmContract contract = crmContractService.queryContractByNum(loanOrderBO.getOrderNum());
//                String orderPoolId = contract.getOwnerOrderPool();
//
//                QueryWrapper<CrmReceivables> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("contract_id", queryContract.getContractId());
//                queryWrapper.eq("collection_type", CrmBusinessConstEnum.回款类型_账单回款.getMsg());
//                List<CrmReceivables> receivablesList = crmReceivablesService.list(queryWrapper);
//
//                QueryWrapper<CrmReceivables> queryWrapper1 = new QueryWrapper<>();
//                queryWrapper1.eq("number",subOrderBo.getPayOrderNum());
//                List<CrmReceivables> crmReceivablesBkList = crmReceivablesService.getBaseMapper().selectList(queryWrapper1);
//                if(CollectionUtils.isEmpty(crmReceivablesBkList)){
//                    crmReceivablesBk.setContractId(contract.getContractId());
//                    crmReceivablesBk.setCustomerId(contract.getCustomerId());
//                    crmReceivablesBk.setStudentId(contract.getStudentId());
//                    crmReceivablesBk.setTeacherId(contract.getTeacherId());
//                    crmReceivablesBk.setOwnerUserId(contract.getOwnerUserId());
//                    crmReceivablesBk.setCreateUserId(contract.getCreateUserId());
//                    if(!CollectionUtils.isEmpty(receivablesList)){
//                        CrmReceivables receivables = receivablesList.get(0);
//                        crmReceivablesBk.setOwnerDeptId(receivables.getOwnerDeptId());
//                    }
//                    crmReceivablesBk.setSource(contract.getSource());
//                    crmReceivablesBk.setTrainingPeriods(contract.getTrainingPeriods());
//                    crmReceivablesBk.setNumber(subOrderBo.getPayOrderNum());
//                    crmReceivablesBk.setCheckStatus(CrmBusinessConstEnum.审核状态_通过.getCode());
//                    crmReceivablesBk.setCheckTime(DateUtils.getNowDate());
//                    crmReceivablesBk.setPaymentTime(subOrderBo.getPayTime());
//                    crmReceivablesBk.setBillReturnType(loanOrderBO.getBillReturnType());
//                    crmReceivablesBk.setMoney(subOrderBo.getFillMoney());
//                    crmReceivablesBk.setRepaymentDueMoney(subOrderBo.getFillMoney());
//                    crmReceivablesBk.setCreateTime(DateUtils.getNowDate());
//                    crmReceivablesBk.setUpdateTime(DateUtils.getNowDate());
//                    crmReceivablesBk.setStudentsCall(subOrderBo.getUserPhone());
//                    crmReceivablesBk.setCourseSource(subOrderBo.getCurriculumName());
//                    crmReceivablesBk.setThreePartOrderNo(subOrderBo.getOrderNum());
//                    crmReceivablesBk.setCollectionType(CrmBusinessConstEnum.回款类型_退款补款.getMsg());
//                    crmReceivablesBk.setOwnerOrderPool(orderPoolId);
//                    crmReceivablesBk.setType(CrmBusinessConstEnum.账单类型_三方账单.getMsg());
//                    crmReceivablesBk.setStudentName(subOrderBo.getRealName());
////            crmReceivables.setRepayPeriods(subOrderBo.getRepayPeriods());
//                    crmReceivablesBk.setCommissionMoney(subOrderBo.getServiceCharge());
////            crmReceivables.setOverdueTime(subOrderBo.getOverdueDate());
//                    crmReceivablesBk.setActualRepaymentDate(subOrderBo.getPayTime());
//                    crmReceivablesBk.setRepaymentDueDate(subOrderBo.getPayTime());
//                    crmReceivablesBk.setBatchId(IdUtil.simpleUUID());
//                    crmReceivablesBk.setRepaymentStatus(CrmRepaidStatusEnum.parse(subOrderBo.getRepaidStatus()).getRemarks());
//                    crmReceivablesBk.setOrderPoolStatus(CrmBusinessConstEnum.账单状态_有效.getMsg());
//                    crmReceivablesBk.setStudentStatus(loanOrderBO.getRepaidStatus() == 5 ? CrmBusinessConstEnum.入学状态_已退学.getMsg() : CrmBusinessConstEnum.入学状态_已入学.getMsg());
//                    crmReceivablesService.save(crmReceivablesBk);
//                }
//            }
//
//            // 做优惠支付子订单删除操作
//            QueryWrapper<CrmReceivables> queryWrapper1 = new QueryWrapper<>();
//            queryWrapper1.eq("contract_id", queryContract.getContractId());
//            queryWrapper1.ne("check_status", 7);
//            queryWrapper1.eq("collection_type", CrmBusinessConstEnum.回款类型_优惠补款.getMsg());
//            List<CrmReceivables> receivablesList = crmReceivablesService.list(queryWrapper1);
//            // 删除优惠支付
//            if(!CollectionUtils.isEmpty(receivablesList)){
//                UpdateWrapper<CrmReceivables> updateWrapper1 = new UpdateWrapper<>();
//                updateWrapper1.set("check_status", 7);
//                updateWrapper1.in("receivables_id", receivablesList.stream().map(CrmReceivables::getReceivablesId).collect(Collectors.toList()));
//                crmReceivablesService.update(updateWrapper1);
//            }
//
//            // 优惠支付
//            CrmReceivables crmReceivablesYH = new CrmReceivables();
//            if(!ObjectUtils.isEmpty(preferentialOrderBo)){
//                CrmContract contract = crmContractService.queryContractByNum(loanOrderBO.getOrderNum());
//                String orderPoolId = contract.getOwnerOrderPool();
//
//                QueryWrapper<CrmReceivables> receivablesWrapper = new QueryWrapper<>();
//                receivablesWrapper.eq("number",preferentialOrderBo.getPreferOrderNum());
//                receivablesWrapper.ne("check_status", 7);
//                List<CrmReceivables> crmReceivablesYHList = crmReceivablesService.getBaseMapper().selectList(receivablesWrapper);
//                if(CollectionUtils.isEmpty(crmReceivablesYHList)){
//                    crmReceivablesYH.setContractId(contract.getContractId());
//                    crmReceivablesYH.setCustomerId(contract.getCustomerId());
//                    crmReceivablesYH.setStudentId(contract.getStudentId());
//                    crmReceivablesYH.setTeacherId(contract.getTeacherId());
//                    crmReceivablesYH.setOwnerUserId(contract.getOwnerUserId());
//                    crmReceivablesYH.setCreateUserId(contract.getCreateUserId());
//                    if(contract.getOwnerUserId() != null){
//                        UserInfo userInfo = UserCacheUtil.getUserInfo(contract.getOwnerUserId());
//                        if(ObjectUtil.isNotEmpty(userInfo)){
//                            crmReceivablesYH.setOwnerDeptId(String.valueOf(userInfo.getDeptId()));
//                        }
//                    }
//                    crmReceivablesYH.setSource(contract.getSource());
//                    crmReceivablesYH.setTrainingPeriods(contract.getTrainingPeriods());
//                    crmReceivablesYH.setNumber(preferentialOrderBo.getPreferOrderNum());
//                    crmReceivablesYH.setCheckStatus(CrmBusinessConstEnum.审核状态_通过.getCode());
//                    crmReceivablesYH.setCheckTime(DateUtils.getNowDate());
//                    crmReceivablesYH.setPaymentTime(preferentialOrderBo.getPayTime());
//                    crmReceivablesYH.setBillReturnType(loanOrderBO.getBillReturnType());
//                    if(preferentialOrderBo.getPayStatus() == 1){
//                        crmReceivablesYH.setMoney(preferentialOrderBo.getPreferPayMoney());
//                    }else{
//                        crmReceivablesYH.setMoney(new BigDecimal(0.00));
//                    }
//                    crmReceivablesYH.setRepaymentDueMoney(preferentialOrderBo.getPreferPayMoney());
//                    crmReceivablesYH.setCreateTime(DateUtils.getNowDate());
//                    crmReceivablesYH.setUpdateTime(DateUtils.getNowDate());
//                    crmReceivablesYH.setStudentsCall(preferentialOrderBo.getUserPhone());
//                    crmReceivablesYH.setCourseSource(preferentialOrderBo.getCurriculumName());
//                    crmReceivablesYH.setThreePartOrderNo(preferentialOrderBo.getOrderNum());
//                    crmReceivablesYH.setCollectionType(CrmBusinessConstEnum.回款类型_优惠补款.getMsg());
//                    crmReceivablesYH.setOwnerOrderPool(orderPoolId);
//                    crmReceivablesYH.setType(CrmBusinessConstEnum.账单类型_三方账单.getMsg());
//                    crmReceivablesYH.setStudentName(preferentialOrderBo.getRealName());
//                    crmReceivablesYH.setCommissionMoney(preferentialOrderBo.getPreferServiceCharge());
//                    crmReceivablesYH.setActualRepaymentDate(preferentialOrderBo.getPayTime());
//                    crmReceivablesYH.setBatchId(IdUtil.simpleUUID());
//                    if(CrmRepaidStatusEnum.已还清.getRemarks().equals(CrmRepaidStatusEnum.parse(loanOrderBO.getRepaidStatus()).getRemarks()) && preferentialOrderBo.getPayStatus() == 1){
//                        crmReceivablesYH.setRepaymentStatus(CrmRepaidStatusEnum.已还清.getRemarks());
//                    }else{
//                        crmReceivablesYH.setRepaymentStatus(CrmRepaidStatusEnum.还款中.getRemarks());
//                    }
//                    crmReceivablesYH.setStudentStatus(loanOrderBO.getRepaidStatus() == 5 ? CrmBusinessConstEnum.入学状态_已退学.getMsg() : CrmBusinessConstEnum.入学状态_已入学.getMsg());
//                    crmReceivablesYH.setOrderPoolStatus(CrmBusinessConstEnum.账单状态_有效.getMsg());
//                    crmReceivablesService.save(crmReceivablesYH);
//                }
//            }
//
//            //更新学员
//            Integer customerId = queryContract.getCustomerId();
//            if (ObjectUtil.isNotEmpty(customerId)) {
//                CrmCustomer crmCustomer = crmCustomerService.getById(customerId);
//                crmCustomer.setRepaymentStatus(CrmRepaidStatusEnum.parse(queryContract.getRepaymentStatus()).getRemarks());
//                if (queryContract.getRepaymentStatus().equals(CrmBusinessConstEnum.还款状态_已退学.getMsg())) {
//                    crmCustomer.setStudentStatus(0);
//                } else {
//                    crmCustomer.setStudentStatus(1);
//                }
//                crmCustomerService.updateById(crmCustomer);
//            }
//            //更新VIP学员
//            Integer studentId = queryContract.getStudentId();
//            CrmStudent student = new CrmStudent();
//            if (ObjectUtil.isNotEmpty(studentId)) {
//                student = crmStudentService.getById(studentId);
//                student.setRepaymentStatus(CrmRepaidStatusEnum.parse(queryContract.getRepaymentStatus()).getRemarks());
//                if (queryContract.getRepaymentStatus().equals(CrmBusinessConstEnum.还款状态_已退学.getMsg())) {
//                    student.setStudentStatus(0);
//                } else {
//                    student.setStudentStatus(1);
//                }
//                crmStudentService.updateById(student);
//            }
//
//            CrmRefund orderRefund = null;
//            if(loanOrderBO.getRepaidStatus() == 5){
//                orderRefund = new CrmRefund();
//                // 设置账单退款数据
//                orderRefund.setContractId(queryContract.getContractId());
//                orderRefund.setCustomerId(queryContract.getCustomerId());
//                orderRefund.setStudentId(studentId);
//                // 退款编号
//                List<AdminConfigBo> configList = adminService.queryConfigByName("numberSetting");
//                AdminConfigBo adminConfig = configList.stream().filter(config -> Objects.equals(CrmEnum.REFUND.getType().toString(), config.getValue())).collect(Collectors.toList()).get(0);
//                if (adminConfig.getStatus() == 1 && StrUtil.isEmpty(orderRefund.getNumber())) {
//                    String result = crmNumberSettingService.generateNumber(adminConfig, null);
//                    if(BeanUtil.isEmpty(orderRefund.getNumber())){
//                        orderRefund.setNumber(result);
//                    }
//                }
//                orderRefund.setSource(queryContract.getSource());
//                orderRefund.setTeacherId(queryContract.getTeacherId());
//                orderRefund.setOwnerUserId(queryContract.getOwnerUserId());
//
//                if(orderRefund.getOwnerUserId() != null){
//                    //设置负责人所在部门
//                    orderRefund.setOwnerDeptId(String.valueOf(UserCacheUtil.getUserInfo(orderRefund.getOwnerUserId()).getDeptId()));
//                }
//
//                orderRefund.setCourseSource(loanOrderBO.getCurriculumName());
//                orderRefund.setCreateTime(DateUtils.getNowDate());
//                orderRefund.setUpdateTime(DateUtils.getNowDate());
//                orderRefund.setCreateUserId(0L);
//                orderRefund.setRefundCategory(CrmBusinessConstEnum.退款状态_账单退款.getMsg());
//                orderRefund.setContractCategory(CrmBusinessConstEnum.账单类别_账单合同.getMsg());
//                orderRefund.setContractMoney(loanOrderBO.getLoanMoney());
//                orderRefund.setMoney(new BigDecimal(0));
//                if (!ObjectUtils.isEmpty(subOrderBo)) {
//                    orderRefund.setBillMoney(subOrderBo.getFillMoney());
//                }else{
//                    orderRefund.setBillMoney(new BigDecimal(0));
//                }
//                orderRefund.setRefundDate(new Date());
//                orderRefund.setReturnTime(loanOrderBO.getApplicationTime());
//                orderRefund.setReturnType(queryContract.getReturnType());
//                orderRefund.setCheckStatus(CrmBusinessConstEnum.审核状态_通过.getCode());
//                if(ObjectUtil.isNotEmpty(studentId)){
//                    orderRefund.setVipPeriods(student.getVipPeriods());
//                }
//                crmReFundService.save(orderRefund);
//            }
//
//            // 删除优惠支付
//            if(!CollectionUtils.isEmpty(receivablesList)){
//                deletePage(receivablesList.stream().map(CrmReceivables::getReceivablesId).collect(Collectors.toList()),CrmEnum.RECEIVABLES.getIndex());
//            }
//                //更新es数据
//            //合同
//            Map<String, Object> esContractmap = BeanUtil.beanToMap(crmContract, false, true);
//            List<CrmModelFiledVO> modelFiledVOList = queryDefaultField(CrmEnum.CONTRACT.getType());
//            modelFiledVOList.forEach(modelField -> {
//                if (esContractmap.get(modelField.getFieldName()) == null) {
//                    esContractmap.remove(modelField.getFieldName());
//                    return;
//                }
//                if (FieldEnum.DATE.getType().equals(modelField.getType())) {
//                    Object vl = esContractmap.remove(modelField.getFieldName());
//                    if (ObjectUtil.isNotEmpty(vl)) {
//                        if (vl instanceof Date) {
//                            esContractmap.put(modelField.getFieldName(), DateUtil.formatDate((Date) vl));
//                        } else if (vl instanceof String) {
//                            esContractmap.put(modelField.getFieldName(), vl.toString());
//                        }
//                    }
//                }
//
//                if (FieldEnum.DATETIME.getType().equals(modelField.getType())) {
//                    Object vl = esContractmap.remove(modelField.getFieldName());
//                    if (ObjectUtil.isNotEmpty(vl)) {
//                        if (vl instanceof Date) {
//                            esContractmap.put(modelField.getFieldName(), DateUtil.formatDateTime((Date) vl));
//                        } else if (vl instanceof String) {
//                            esContractmap.put(modelField.getFieldName(), vl.toString());
//                        }
//                    }
//
//                }
//            });
//
//            ElasticUtil.updateField(elasticsearchRestTemplate, esContractmap, queryContract.getContractId(), CrmEnum.CONTRACT.getIndex());
//            List<CrmModelFiledVO> modelFiledVOListRecivable = queryDefaultField(CrmEnum.RECEIVABLES.getType());
//
//            //回款es
//            for (CrmReceivables crmReceivables : crmReceivablesList) {
//                Map<String, Object> esReceivablesMap = BeanUtil.beanToMap(crmReceivables, false, true);
//                modelFiledVOListRecivable.forEach(modelField -> {
//                    if (esReceivablesMap.get(modelField.getFieldName()) == null) {
//                        esReceivablesMap.remove(modelField.getFieldName());
//                        return;
//                    }
//                    if (FieldEnum.DATE.getType().equals(modelField.getType())) {
//                        Object vl = esReceivablesMap.remove(modelField.getFieldName());
//                        if (ObjectUtil.isNotEmpty(vl)) {
//                            if (vl instanceof Date) {
//                                esReceivablesMap.put(modelField.getFieldName(), DateUtil.formatDate((Date) vl));
//                            } else if (vl instanceof String) {
//                                esReceivablesMap.put(modelField.getFieldName(), vl.toString());
//                            }
//                        }
//                    }
//
//                    if (FieldEnum.DATETIME.getType().equals(modelField.getType())) {
//                        Object vl = esReceivablesMap.remove(modelField.getFieldName());
//                        if (ObjectUtil.isNotEmpty(vl)) {
//                            if (vl instanceof Date) {
//                                esReceivablesMap.put(modelField.getFieldName(), DateUtil.formatDateTime((Date) vl));
//                            } else if (vl instanceof String) {
//                                esReceivablesMap.put(modelField.getFieldName(), vl.toString());
//                            }
//                        }
//                    }
//                });
//                esReceivablesMap.put("contractNum", queryContract.getNum());
//                esReceivablesMap.put("contractMoney", queryContract.getMoney());
//                esReceivablesMap.put("ownerUserId", queryContract.getOwnerUserId());
//                if(queryContract.getOwnerUserId() != null){
//                    esReceivablesMap.put("ownerUserName", adminService.queryUserName(queryContract.getOwnerUserId()));
//                }
//                esReceivablesMap.put("teacherId", queryContract.getTeacherId());
//                if(queryContract.getTeacherId() != null){
//                    esReceivablesMap.put("teacherName", adminService.queryUserName(queryContract.getTeacherId()));
//                }
//                ElasticUtil.updateField(elasticsearchRestTemplate, esReceivablesMap, crmReceivables.getReceivablesId(), CrmEnum.RECEIVABLES.getIndex());
//            }
//            //补款es
//            if (!ObjectUtils.isEmpty(subOrderBo)) {
//                CrmModelSaveBO receivablesModel = new CrmModelSaveBO();
//
//                receivablesModel.setEntity(BeanUtil.beanToMap(crmReceivablesBk));
//
//                if(queryContract.getCustomerId() != null){
//                    String customerName = crmCustomerService.getCustomerName(queryContract.getCustomerId());
//                    receivablesModel.getEntity().put("customerName", customerName);
//                }
//
//                receivablesModel.getEntity().put("contractNum", queryContract.getNum());
//                receivablesModel.getEntity().put("contractMoney", queryContract.getMoney());
//                receivablesModel.getEntity().put("ownerUserId", queryContract.getOwnerUserId());
//                if(queryContract.getOwnerUserId() != null){
//                    receivablesModel.getEntity().put("ownerUserName", adminService.queryUserName(queryContract.getOwnerUserId()));
//                }
//                receivablesModel.getEntity().put("createUserId", crmReceivablesBk.getCreateUserId());
//                if(crmReceivablesBk.getCreateUserId() != null){
//                    receivablesModel.getEntity().put("createUserName", adminService.queryUserName(crmReceivablesBk.getCreateUserId()));
//                }
//                receivablesModel.getEntity().put("ownerDeptId", crmReceivablesBk.getOwnerDeptId());
//                if(crmReceivablesBk.getOwnerDeptId() != null){
//                    String deptName = this.adminService.queryDeptName(Integer.valueOf(String.valueOf(crmReceivablesBk.getOwnerDeptId())));
//                    receivablesModel.getEntity().put("ownerDeptName", deptName);
//                }
//                receivablesModel.getEntity().put("teacherId", queryContract.getTeacherId());
//                if(queryContract.getTeacherId() != null){
//                    receivablesModel.getEntity().put("teacherName", adminService.queryUserName(queryContract.getTeacherId()));
//                }
//                savePageByLable(receivablesModel, crmReceivablesBk.getReceivablesId(), false, CrmEnum.RECEIVABLES.getType());
//            }
//
//            //账单退款ES
//            if(!ObjectUtils.isEmpty(orderRefund)){
//                CrmModelSaveBO refundModel = new CrmModelSaveBO();
//                refundModel.setEntity(BeanUtil.beanToMap(orderRefund));
//                refundModel.getEntity().put("contractNum", crmContract.getNum());
//                refundModel.getEntity().put("ownerUserId", orderRefund.getOwnerUserId());
//                if(queryContract.getOwnerUserId() != null){
//                    refundModel.getEntity().put("ownerUserName", adminService.queryUserName(orderRefund.getOwnerUserId()));
//                }else{
//                    refundModel.getEntity().put("ownerUserName","");
//                }
//                refundModel.getEntity().put("ownerDeptId", orderRefund.getOwnerDeptId());
//                if(orderRefund.getOwnerDeptId() != null){
//                    String deptName = this.adminService.queryDeptName(Integer.valueOf(String.valueOf(orderRefund.getOwnerDeptId())));
//                    refundModel.getEntity().put("ownerDeptName", deptName);
//                }else{
//                    refundModel.getEntity().put("ownerDeptName","");
//                }
//                refundModel.getEntity().put("teacherId", orderRefund.getTeacherId());
//                if(orderRefund.getTeacherId() != null){
//                    refundModel.getEntity().put("teacherName", adminService.queryUserName(orderRefund.getTeacherId()));
//                }else{
//                    refundModel.getEntity().put("teacherName","");
//                }
//
//                if(ObjectUtil.isNotEmpty(studentId)){
//                    refundModel.getEntity().put("studentName", student.getCustomerName());
//                }else{
//                    refundModel.getEntity().put("studentName", "");
//                }
//
//                savePageByLable(refundModel, orderRefund.getRefundId(), false, CrmEnum.REFUND.getType());
//            }
//
//            //优惠支付es
//            if (!ObjectUtils.isEmpty(preferentialOrderBo)) {
//                CrmModelSaveBO receivablesModel = new CrmModelSaveBO();
//
//                receivablesModel.setEntity(BeanUtil.beanToMap(crmReceivablesYH));
//
//                if(queryContract.getCustomerId() != null){
//                    String customerName = crmCustomerService.getCustomerName(queryContract.getCustomerId());
//                    receivablesModel.getEntity().put("customerName", customerName);
//                }
//
//                receivablesModel.getEntity().put("contractNum", queryContract.getNum());
//                receivablesModel.getEntity().put("contractMoney", queryContract.getMoney());
//                receivablesModel.getEntity().put("ownerUserId", queryContract.getOwnerUserId());
//                if(queryContract.getOwnerUserId() != null){
//                    receivablesModel.getEntity().put("ownerUserName", adminService.queryUserName(queryContract.getOwnerUserId()));
//                }
//                receivablesModel.getEntity().put("createUserId", crmReceivablesYH.getCreateUserId());
//                if(crmReceivablesYH.getCreateUserId() != null){
//                    receivablesModel.getEntity().put("createUserName", adminService.queryUserName(crmReceivablesYH.getCreateUserId()));
//                }
//                receivablesModel.getEntity().put("ownerDeptId", crmReceivablesYH.getOwnerDeptId());
//                if(crmReceivablesYH.getOwnerDeptId() != null){
//                    String deptName = this.adminService.queryDeptName(Integer.valueOf(String.valueOf(crmReceivablesYH.getOwnerDeptId())));
//                    receivablesModel.getEntity().put("ownerDeptName", deptName);
//                }
//                receivablesModel.getEntity().put("teacherId", queryContract.getTeacherId());
//                if(queryContract.getTeacherId() != null){
//                    receivablesModel.getEntity().put("teacherName", adminService.queryUserName(queryContract.getTeacherId()));
//                }
//                savePageByLable(receivablesModel, crmReceivablesYH.getReceivablesId(), false, CrmEnum.RECEIVABLES.getType());
//            }
//
//            //更新学员
//            if (ObjectUtil.isNotEmpty(customerId)) {
//                Map<String, Object> mapCustomer = new HashMap<>();
//                mapCustomer.put("repaymentStatus", queryContract.getRepaymentStatus());
//                if (queryContract.getRepaymentStatus().equals(CrmBusinessConstEnum.还款状态_已退学.getMsg())) {
//                    mapCustomer.put("studentStatus", 0);
//                } else {
//                    mapCustomer.put("studentStatus", 1);
//                }
//                ElasticUtil.updateField(elasticsearchRestTemplate, mapCustomer, customerId, CrmEnum.CUSTOMER.getIndex());
//
//            }
//            //更新VIP学员
//            if (ObjectUtil.isNotEmpty(studentId)) {
//                Map<String, Object> mapStudent = new HashMap<>();
//                mapStudent.put("repaymentStatus", queryContract.getRepaymentStatus());
//                if (queryContract.getRepaymentStatus().equals(CrmBusinessConstEnum.还款状态_已退学.getMsg())) {
//                    mapStudent.put("studentStatus", 0);
//                } else {
//                    mapStudent.put("studentStatus", 1);
//                }
//                ElasticUtil.updateField(elasticsearchRestTemplate, mapStudent, studentId, CrmEnum.STUDENT.getIndex());
//            }
//
//            if(!ObjectUtil.equal(oldContract.getRepaymentStatus(),queryContract.getRepaymentStatus())){
//                if(queryContract.getRepaymentStatus().equals(CrmBusinessConstEnum.还款状态_已退学.getMsg())){
//                    if(student.getAssistantUserId() != null){
//                        // 账单合同退学新增消息
//                        AdminMessage adminMessage = new AdminMessage();
//                        adminMessage.setTitle(student.getCustomerName());
//                        adminMessage.setContent(queryContract.getNum());
//                        adminMessage.setTypeId(studentId);
//                        adminMessage.setCreateUser(0L);
//                        adminMessage.setRecipientUser(student.getAssistantUserId());
//                        adminMessage.setLabel(6);
//                        adminMessage.setType(AdminMessageEnum.CRM_CONTRACT_DROPOUT.getType());
//                        adminMessage.setIsRead(0);
//                        adminMessageService.saveOrUpdateMessage(adminMessage);
//                    }
//                }else if(queryContract.getRepaymentStatus().equals(CrmBusinessConstEnum.还款状态_已逾期.getMsg())){
//                    if(student.getAssistantUserId() != null){
//                        // 账单合同逾期新增消息
//                        AdminMessage adminMessage = new AdminMessage();
//                        adminMessage.setTitle(student.getCustomerName());
//                        adminMessage.setContent(queryContract.getNum());
//                        adminMessage.setTypeId(studentId);
//                        adminMessage.setCreateUser(0L);
//                        adminMessage.setRecipientUser(student.getAssistantUserId());
//                        adminMessage.setLabel(6);
//                        adminMessage.setType(AdminMessageEnum.CRM_CONTRACT_OVERDUE.getType());
//                        adminMessage.setIsRead(0);
//                        adminMessageService.saveOrUpdateMessage(adminMessage);
//                    }
//                }
//            }
//
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new RuntimeException("系统异常" + e);
//        } finally {
//            redisCache.unlock(key, value);
//        }
//        return R.ok();
//    }
//
//    @Override
//    public String[] appendSearch() {
//        return new String[0];
//    }
//
//    @Override
//    public void setOtherField(Map<String, Object> map) {
//
//    }
//
//    public CrmEnum getLabel() {
//        return null;
//    }
//
//    @Override
//    public List<CrmModelFiledVO> queryDefaultField() {
//        return null;
//    }
//
//
//    public List<CrmModelFiledVO> queryDefaultField(Integer lable) {
//        if (lable == CrmEnum.CONTRACT.getType()) {
//            List<CrmModelFiledVO> filedList = SpringUtils.getBean(ICrmFieldService.class).queryField(lable);
//            filedList.add(new CrmModelFiledVO("lastTime", FieldEnum.DATETIME, 1));
//            filedList.add(new CrmModelFiledVO("updateTime", FieldEnum.DATETIME, 1));
//            filedList.add(new CrmModelFiledVO("createTime", FieldEnum.DATETIME, 1));
//            filedList.add(new CrmModelFiledVO("roUserId", FieldEnum.CHECKBOX, 1));
//            filedList.add(new CrmModelFiledVO("rwUserId", FieldEnum.CHECKBOX, 1));
//            filedList.add(new CrmModelFiledVO("ownerUserId", FieldEnum.USER, 1));
//            filedList.add(new CrmModelFiledVO("createUserId", FieldEnum.USER, 1));
//            filedList.add(new CrmModelFiledVO("companyUserId", FieldEnum.USER, 1));
//            filedList.add(new CrmModelFiledVO("checkStatus", FieldEnum.TEXT, 1));
//            filedList.add(new CrmModelFiledVO("contractId", FieldEnum.TEXT, 1));
//            filedList.add(new CrmModelFiledVO("receivedMoney", FieldEnum.TEXT, 1));
//            filedList.add(new CrmModelFiledVO("unreceivedMoney", FieldEnum.TEXT, 1));
//            return filedList;
//        }
//        if (lable == CrmEnum.RECEIVABLES.getType()) {
//            List<CrmModelFiledVO> filedList = SpringUtils.getBean(ICrmFieldService.class).queryField(lable);
//            filedList.add(new CrmModelFiledVO("lastTime", FieldEnum.DATETIME, 1));
//            filedList.add(new CrmModelFiledVO("updateTime", FieldEnum.DATETIME, 1));
//            filedList.add(new CrmModelFiledVO("createTime", FieldEnum.DATETIME, 1));
//            filedList.add(new CrmModelFiledVO("ownerUserId", FieldEnum.USER, 1));
//            filedList.add(new CrmModelFiledVO("createUserId", FieldEnum.USER, 1));
//            filedList.add(new CrmModelFiledVO("createDeptId", FieldEnum.STRUCTURE, 1));
//            filedList.add(new CrmModelFiledVO("checkStatus", FieldEnum.TEXT, 1));
//            filedList.add(new CrmModelFiledVO("planId", FieldEnum.TEXT, 1));
//            filedList.add(new CrmModelFiledVO("createDeptName", FieldEnum.TEXT, 1));
//            filedList.add(new CrmModelFiledVO("courseSource", FieldEnum.TEXT, 1));
//            //filedList.add(new CrmModelFiledVO("salesUserId", FieldEnum.USER,1));
//            return filedList;
//        }
//        if(lable == CrmEnum.REFUND.getType()){
//            List<CrmModelFiledVO> filedList = SpringUtils.getBean(ICrmFieldService.class).queryField(lable);
//            filedList.add(new CrmModelFiledVO("updateTime", FieldEnum.DATETIME, 1));
//            filedList.add(new CrmModelFiledVO("createTime", FieldEnum.DATETIME, 1));
//            filedList.add(new CrmModelFiledVO("ownerUserId", FieldEnum.USER, 1));
//            filedList.add(new CrmModelFiledVO("createUserId", FieldEnum.USER, 1));
//            filedList.add(new CrmModelFiledVO("ownerDeptId", FieldEnum.STRUCTURE, 1));
//            filedList.add(new CrmModelFiledVO("checkStatus", FieldEnum.TEXT, 1));
//            filedList.add(new CrmModelFiledVO("courseSource", FieldEnum.TEXT, 1));
//            return filedList;
//        }
//        return null;
//    }


}
